package com.kyxx.topics.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.net.ResponseListener;
import com.kyxx.topics.net.RestClient;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.Constants;
import com.kyxx.topics.utils.ScreenSizeUtils;
import com.kyxx.topics.utils.SizeUtils;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.Tools;
import com.kyxx.topics.view.CircleImageView;
import com.kyxx.topics.view.MyCommonTitle;
import com.kyxx.topics.view.UIDialog;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.DiskCacheUtils;
import com.nostra13.universalimageloader.utils.MemoryCacheUtils;

import org.json.JSONException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import cz.msebera.android.httpclient.Header;


/**
 * Created by Administrator on 2016/7/23.
 */
public class UserInfoActivity extends BaseActivity implements View.OnClickListener {
    private CircleImageView imgUserAvatar;
    private TextView tvUserId;
    private TextView tvNickName, tvUserMobile;
    private Button btn_logout;
    private LinearLayout layUserAvatar, layoutNickName, laySetPsw, layBindMobile, layUserAddress;

    private String timeString;
    private File f;
    private int type;//type为1修改昵称对话框  type为8显示修改头像弹框   type为9显示绑定手机弹框
    private Dialog alertDialog;
    private View view;
    private EditText editContent;
    private TextView tvTitle;
    private Button btn_1;
    private DisplayImageOptions options = new DisplayImageOptions.Builder()
            // 设置图片在下载期间显示的图片
            .showImageOnLoading(R.mipmap.icon_user_default)
            // 设置图片Uri为空或是错误的时候显示的图片
            .showImageForEmptyUri(R.mipmap.icon_user_default)
            // 设置图片加载/解码过程中错误时候显示的图片
            .showImageOnFail(R.mipmap.icon_user_default)
            .cacheInMemory(true)
            // 设置下载的图片是否缓存在内存中
            .cacheOnDisk(true)
            // 设置下载的图片是否缓存在SD卡中
            .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型
//                .displayer(new RoundedBitmapDisplayer(9999))
            .build();

    @Override
    protected void loadTopBar(String title) {
        super.loadTopBar(title);
        top_bar_tv_left.setVisibility(View.GONE);
        top_bar_iv_left.setVisibility(View.VISIBLE);
        top_bar_tv_right.setVisibility(View.GONE);
        top_bar_iv_right.setVisibility(View.GONE);
        top_bar_iv_left.setImageDrawable(getResources().getDrawable(R.drawable.ic_arrow_right));
        top_bar_iv_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_user_info);
    }

    @Override
    protected void findViewById() {
        loadTopBar("个人资料");
        imgUserAvatar = (CircleImageView) findViewById(R.id.img_user_avatar);//头像
        tvUserId = (TextView) findViewById(R.id.tv_user_id);//id
        tvNickName = (TextView) findViewById(R.id.tv_nick_name);//昵称
        tvUserMobile = (TextView) findViewById(R.id.tv_user_mobile);//绑定的手机
        layUserAvatar = (LinearLayout) findViewById(R.id.layout_user_avatar);
        layoutNickName = (LinearLayout) findViewById(R.id.layout_user_nick_name);
        laySetPsw = (LinearLayout) findViewById(R.id.lay_user_set_psw);//设置密码
        layBindMobile = (LinearLayout) findViewById(R.id.lay_user_bind_mobile);//绑定手机号码
        layUserAddress = (LinearLayout) findViewById(R.id.lay_user_address);//地址管理
        btn_logout = (Button) findViewById(R.id.btn_logout);//退出
    }

    @Override
    protected void setListener() {
        layUserAvatar.setOnClickListener(this);
        layUserAddress.setOnClickListener(this);
        laySetPsw.setOnClickListener(this);
        layoutNickName.setOnClickListener(this);
        layBindMobile.setOnClickListener(this);
        btn_logout.setOnClickListener(this);
    }

    @Override
    protected void processLogic() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    /**
     * 获取个人资料
     */
    private void requestData() {
        ImageLoader.getInstance().displayImage(BaseApp.getModel().getAvatar(), imgUserAvatar, options);
        tvUserId.setText(BaseApp.getModel().getId());
        tvNickName.setText(BaseApp.getModel().getNickname());
        tvUserMobile.setText(BaseApp.getModel().getMobile());
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.layout_user_avatar://头像
                type = 8;
//                UIDialog.ForThreeBtn(this, new String[]{"拍照", "从相册选择", "取消"}, this);
                new android.support.v7.app.AlertDialog.Builder(context).setTitle("修改头像").setItems(new String[]{"拍照", "从相册选择"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i) {
                            case 0:
              /* 拍照 */
                                UIDialog.closeDialog();
                                Date date = new Date(System.currentTimeMillis());
                                SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMddHHmmss", new Locale("zh", "CN"));
                                timeString = dateFormat.format(date);
                                createSDCardDir();
                                Intent shootIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                shootIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
                                        new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera", timeString + ".jpg")));
                                startActivityForResult(shootIntent, 2);
                                break;
                            case 1:
         /* 从相册中选取 */
                                Intent photoIntent = new Intent(Intent.ACTION_PICK, null);
                                photoIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                startActivityForResult(photoIntent, 1);
                                break;
                        }
                    }
                }).setNegativeButton("取消",null).show();
                break;
            case R.id.layout_user_nick_name://修改昵称
                type = 1;
                showEditDialog(type);
//                final EditText tv = new EditText(context);
//                new android.support.v7.app.AlertDialog.Builder(this).setTitle("修改昵称").setView(tv).setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialogInterface, int i) {
//                        submitEditData(type, tv.getText().toString());
//                    }
//                }).setNegativeButton("取消", null).show();
                break;
            case R.id.lay_user_set_psw://设置密码
                startActivity(new Intent(UserInfoActivity.this, UserSetPswActivity.class));
                break;
            case R.id.lay_user_bind_mobile://绑定手机
                type = 9;
//                UIDialog.ForFourBtn(this, new String[]{"绑定手机号码", "解绑", "更换手机号码", "取消"}, this);
                new android.support.v7.app.AlertDialog.Builder(context).setTitle("绑定手机").setItems(new String[]{"绑定手机号码", "解绑", "更换手机号码"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        switch (i) {
                            case 0:
                                if (StringUtil.isEmpty(BaseApp.getModel().getMobile())) {
                                    UIDialog.closeDialog();
                                    startActivity(new Intent(UserInfoActivity.this, UserBindMobile.class).putExtra("type", 1));//绑定
                                } else {
                                    Tools.toast(UserInfoActivity.this, "您已经绑定过手机了！");
                                }
                                break;
                            case 1:
                                Dialog dialog = new android.support.v7.app.AlertDialog.Builder(UserInfoActivity.this)
                                        .setTitle("沂蒙温馨提示")
                                        .setMessage("您真的要解绑这个手机号吗？")
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                unBindMobile();
                                            }
                                        })
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialogInterface, int i) {
                                                dialogInterface.dismiss();
                                            }
                                        })
                                        .create();
                                dialog.show();
                                dialog.getWindow();
                                break;
                            case 2:
                                startActivity(new Intent(UserInfoActivity.this, UserBindMobile.class).putExtra("type", 2));//换绑
                                break;
                        }
                    }
                }).setNegativeButton("取消",null).show().getWindow();
                break;
            case R.id.lay_user_address://地址管理
                startActivity(new Intent(UserInfoActivity.this, UserAddressManageActivity.class));
                break;
            case R.id.btn_logout://退出登录
                BaseApp.getModel().clear();
                finish();
                break;
//            case R.id.dialog_modif_1:
//                    /* 拍照 */
//                UIDialog.closeDialog();
//                Date date = new Date(System.currentTimeMillis());
//                SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMddHHmmss", new Locale("zh", "CN"));
//                timeString = dateFormat.format(date);
//                createSDCardDir();
//                Intent shootIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//                shootIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
//                        new File(Environment.getExternalStorageDirectory() + "/DCIM/Camera", timeString + ".jpg")));
//                startActivityForResult(shootIntent, 2);
//                break;
//            case R.id.dialog_modif_5:
//                if (StringUtil.isEmpty(BaseApp.getModel().getMobile())) {
//                    UIDialog.closeDialog();
//                    startActivity(new Intent(UserInfoActivity.this, UserBindMobile.class).putExtra("type", 1));//绑定
//                } else {
//                    Tools.toast(UserInfoActivity.this, "您已经绑定过手机了！");
//                }
//                break;
//            case R.id.dialog_modif_2:
//                UIDialog.closeDialog();
//                if (type == 8) {
//                   /* 从相册中选取 */
//                    Intent photoIntent = new Intent(Intent.ACTION_PICK, null);
//                    photoIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
//                    startActivityForResult(photoIntent, 1);
//                } else if (type == 9) {
//                    showEditDialog(type);
//                }
//                break;
//            case R.id.dialog_modif_3://取消
//                if (type == 8) {
//                    UIDialog.closeDialog();
//                } else if (type == 9) {
//                    startActivity(new Intent(UserInfoActivity.this, UserBindMobile.class).putExtra("type", 2));//换绑
//                    UIDialog.closeDialog();
//                }
//            case R.id.dialog_modif_4://取消
//                UIDialog.closeDialog();
//                break;
        }
    }

    private void showEditDialog(final int type) {

//        alertDialog = new Dialog(UserInfoActivity.this, R.style.Translucent_NoTitle);
//        Window window = alertDialog.getWindow();
//        window.setGravity(Gravity.CENTER); // 此处可以设置dialog显示的位置
        if (type == 1) {//type用于控制显示弹框的内容, 3 为修改性别   status用于控制调用接口提交相应的数据到服务器
            view = LayoutInflater.from(UserInfoActivity.this).inflate(R.layout.dialog_edit_user_nickname, null);
            editContent = (EditText) view.findViewById(R.id.ed_nickname);// 昵称
            tvTitle = (TextView) view.findViewById(R.id.tv_title);// 标题
            tvTitle.setText("修改昵称");
            editContent.setText(tvNickName.getText().toString());//內容为修改前的内容
            editContent.setSelection(editContent.length());//光标定在内容末尾
        } else if (type == 9) {
            Dialog dialog = new AlertDialog.Builder(UserInfoActivity.this)
                    .setTitle("沂蒙温馨提示")
                    .setMessage("您真的要解绑这个手机号吗？")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            unBindMobile();
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    })
                    .create();
            dialog.show();
        }
        if (type != 9) {
//            alertDialog.setContentView(view);
            alertDialog=new android.support.v7.app.AlertDialog.Builder(UserInfoActivity.this).setView(view).setTitle("修改昵称").setNegativeButton("取消",null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    if (type == 1) {
                        submitEditData(type, editContent.getText().toString().trim());
                    }
                }
            }).create();
//            TextView tvCancle = (TextView) view.findViewById(R.id.btn_cancel);//取消
//            TextView tvConfirm = (TextView) view.findViewById(R.id.btn_confirm);//确定退出
//
//            tvCancle.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    alertDialog.dismiss();
//                }
//            });
//            tvConfirm.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    alertDialog.dismiss();
//                    if (type == 1) {
//                        submitEditData(type, editContent.getText().toString().trim());
//                    }
//                }
//            });
            alertDialog.show();
            alertDialog.getWindow();
        }
    }

    /**
     * 解绑手机
     */
    private void unBindMobile() {

    }

    /**
     * 提交数据到服务器
     *
     * @param content
     */
    private void submitEditData(final int type, final String content) {
        RequestParams params = new RequestParams();
        params.put("uid", BaseApp.getModel().getId());
        params.put("nickname", editContent.getText().toString().trim());
        RestClient.post(UrlUtils.UPDATEAVATAR, params, UserInfoActivity.this, new ResponseListener(UserInfoActivity.this, true) {

            @Override
            public void success(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                try {
                    if (jsonObject.getInt("code") == 0) {
                        Tools.toast(UserInfoActivity.this, "昵称修改成功！");
                        if (type == 1) {
                            tvNickName.setText(content);
                            BaseApp.getModel().setNickname(content);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                Tools.toast(UserInfoActivity.this, "昵称修改失败！");
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
            /* 如果是直接从相册获取 */
                try {
                    startPhotoZoom(data.getData());
                } catch (Exception e) {
                    Toast.makeText(this, "您没有选择任何照片", Toast.LENGTH_LONG).show();
                }
                break;
            case 2:
            /* 如果是调用相机拍照，图片设置名字和路径 */
                File temp = new File(
                        Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + timeString + ".jpg");
                startPhotoZoom(Uri.fromFile(temp));
                break;
            case 3:
            /* 取得裁剪后的图片 */
                if (data != null) {
                    setPicToView(data);
                }
                break;
            case 11:
//                requestData();
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void createSDCardDir() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            // 创建一个文件夹对象，赋值为外部存储器的目录
            File sdcardDir = Environment.getExternalStorageDirectory();
            // 得到一个路径，内容是sdcard的文件夹路径和名字
            String path = sdcardDir.getPath() + "/DCIM/Camera";
            File path1 = new File(path);
            if (!path1.exists()) {
                // 若不存在，创建目录，可以在应用启动的时候创建
                path1.mkdirs();
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 60);
        intent.putExtra("outputY", 60);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 3);
    }

    /**
     * 保存裁剪之后的图片数据
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            // Drawable drawable = new BitmapDrawable(photo);
            /* 下面注释的方法是将裁剪之后的图片以Base64Coder的字符方式上 传到服务器，QQ头像上传采用的方法跟这个类似 */
            savaBitmap(photo);
            // avatar_head_image.setBackgroundDrawable(drawable);
        }
    }

    /**
     * 将剪切后的图片保存到本地图片上！
     */
    public void savaBitmap(Bitmap bitmap) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMddHHmmss", new Locale("zh", "CN"));
        String cutnameString = dateFormat.format(date);
        String filename = Environment.getExternalStorageDirectory().getPath() + "/" + cutnameString + ".jpg";
        f = new File(filename);
        FileOutputStream fOut = null;
        try {
            f.createNewFile();
            fOut = new FileOutputStream(f);
        } catch (Exception e) {
            e.printStackTrace();
        }
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);// 把Bitmap对象解析成流
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        imgUserAvatar.setImageBitmap(bitmap);
        uploadAvatar(f);
    }

    /**
     * 上传图片更新服务器数据
     *
     * @param
     */
    private void uploadAvatar(File file) {
        RequestParams params = new RequestParams();
        params.put("uid", BaseApp.getModel().getId());
        try {
            params.put("avatar", file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        RestClient.post(UrlUtils.UPDATEAVATAR, params, UserInfoActivity.this, new ResponseListener(UserInfoActivity.this, true) {
                    @Override
                    public void success(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                        try {
                            Tools.toast(UserInfoActivity.this, "上传成功！");
                            if (BaseApp.getModel().getAvatar() != null) {
                                DiskCacheUtils.removeFromCache(BaseApp.getModel().getAvatar(), ImageLoader.getInstance().getDiskCache());
                                MemoryCacheUtils.removeFromCache(BaseApp.getModel().getAvatar(), ImageLoader.getInstance().getMemoryCache());
                            }
                            String avatar = jsonObject.getJSONObject("data").getString("path");
                            BaseApp.getModel().setAvatar(UrlUtils.APIHTTP + avatar);
                            ImageLoader.getInstance().displayImage(UrlUtils.APIHTTP + avatar, imgUserAvatar, options);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(int arg0, Header[] arg1, org.json.JSONObject jsonObject) {
                        Tools.toast(UserInfoActivity.this, "上传失败！");
                    }
                }
        );
    }
}
